import React from 'react';
import { SortableContainer, SortableElement, arrayMove } from 'react-sortable-hoc';
import type { SortEndHandler } from 'react-sortable-hoc';
// import { arrayMoveImmutable } from 'array-move';
import type { ImagesListItem, ImagesListParams } from '../data';
import ImageItem from './ImageItem';
import type { ImageItemProps } from './ImageItem';
import styles from './index.less';

export type SortableImageProps = {
  imagesList: ImagesListItem[];
  setImagesList: (list: React.SetStateAction<ImagesListItem[]>) => void;
  getImages: (params?: ImagesListParams) => void;
  searchTitle: string;
  paginationData: {
    defaultCurrent: number;
    pageSize: number;
  };
};

const SortableItem = SortableElement((params: ImageItemProps) => <ImageItem {...params} />);

const SortableList = SortableContainer((props: SortableImageProps) => {
  const { imagesList, getImages, searchTitle, paginationData } = props;
  return (
    <div className={styles['image-container']}>
      {imagesList.map((item: ImagesListItem, index: number) => (
        <SortableItem
          index={index}
          key={item.key}
          {...(item as Omit<ImagesListItem, 'key'>)}
          getImages={getImages}
          searchTitle={searchTitle}
          paginationData={paginationData}
        />
      ))}
    </div>
  );
});

const SortableImages = (props: SortableImageProps) => {
  const { imagesList, setImagesList } = props;
  const onSortEnd: SortEndHandler = ({ oldIndex, newIndex }) => {
    setImagesList(() => arrayMove(imagesList, oldIndex, newIndex));
  };

  return <SortableList {...props} onSortEnd={onSortEnd} axis="xy" />;
};

export default SortableImages;
